//app.js
App({
	onLaunch: function () {
	},
	onShow: function () {
		console.log(getCurrentPages())
	},
	onHide: function () {
		console.log(getCurrentPages())
	},
	onError: function (msg) {
		console.log(msg)
	},
	util: require('we7/resource/js/util.js'),
  editTabBar: function () {
    var tabbar = this.globalData.tabbar,
      currentPages = getCurrentPages(),
      _this = currentPages[currentPages.length - 1],
      pagePath = _this.__route__;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (var i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },
	tabBar: {
		"color": "#123",
		"selectedColor": "#000000",
    "borderStyle": "#black",
		"backgroundColor": "#fff",
		"list": [
			{
				"pagePath": "/we7/pages/index/index",
				"iconPath": "/we7/resource/icon/home.png",
				"selectedIconPath": "/we7/resource/icon/homeselect.png",
				"text": "首页"
			},
			{
				"pagePath": "/we7/pages/user/index/index",
				"iconPath": "/we7/resource/icon/user.png",
				"selectedIconPath": "/we7/resource/icon/userselect.png",
				"text": "我的"
			}
		]
	},
	globalData:{
		userInfo : null,
    tabbar: {
      color: "#333",
      selectedColor: "#000000",
      backgroundColor: "#fff",
      borderStyle: "#d5d5d5",
      list: [
        {
          pagePath: "/zh_dianc/pages/seller/gzt",
          text: "工作台",
          iconPath: "/zh_dianc/pages/images/gzt@3x.png",
          selectedIconPath: "/zh_dianc/pages/images/gztxz@3x.png",
          selected: true
        },
        {
          pagePath: "/zh_dianc/pages/seller/dd",
          text: "订单",
          iconPath: "/zh_dianc/pages/images/dd@3x.png",
          selectedIconPath: "/zh_dianc/pages/images/ddxz@3x.png",
          selected: false
        },
        {
          pagePath: "/zh_dianc/pages/seller/shezhi",
          text: "设置",
          iconPath: "/zh_dianc/pages/images/sz@3x.png",
          selectedIconPath: "/zh_dianc/pages/images/szxz@3x.png",
          selected: false
        }
      ],
      position: "bottom"
    }
	},
  //获取商品分类 
  getTypeList: function (store_id){
    let that = this,
      curPage = this.getCurrentPages();  
    this.util.request({
      'url': 'entry/wxapp/AppDishesType',
      'cachetime': '0',
      'data': { "store_id": store_id},
      success: function (res) {
        curPage.setData({
          "typeList": res.data
        })
      },
    })
  },
  //获取商品集合（列表）
  getFoodList: function (store_id) {
    let that = this,
      curPage = this.getCurrentPages();
    this.util.request({
      'url': 'entry/wxapp/AppDishes',
      'cachetime': '0',
      'data': { "store_id": store_id },
      success: function (res) {
        console.log(res);
        console.log('-----------------------------------------------------------------------------')
        curPage.setData({
          "foodList": res.data
        });
        curPage.setShowFoodList();
      },
    })
  },
  getCurrentPages: function () {
    var pages = getCurrentPages();    //获取加载的页面( 页面栈 )
    return pages[pages.length - 1];
  },
  //搜索
  getSearchRes: function (key, store_id) {
    let that = this;
    this.util.request({
      'url': 'entry/wxapp/SearchAppDishes',//搜索菜品接口
      'cachetime': '0',
      'data': { "name": key, "store_id": store_id},
      success: function (res) {
        that.getCurrentPages().setData({
          "searchList": res.data
        })
      },
    })
  },
  //根据id获取菜品详情
  getDetailById:function(id){
    let that = this;
    this.util.request({
      'url': 'entry/wxapp/AppDishesInfo',//搜索菜品接口
      'cachetime': '0',
      'data': { "id": id },
      success: function (res) {
        that.getCurrentPages().setData({
          "foodObj": res.data
        })
      },
    })
  },
  //查询订单
  getMyorder:function(userId){
    let that = this;
    this.util.request({
      'url': 'entry/wxapp/Myorder',//搜索菜品接口
      'cachetime': '0',
      'data': { "user_id": userId },
      success: function (res) {
        console.log("查询用户的订单")
        console.log(res)

        that.getCurrentPages().setData({
          "myOrder": res.data,
          "orderCount":res.data.length
        })
      },
    })
  },
  //改变用户选中的商品
  //model 如果 != 1 删除这个item
  changeChosedFood:function(goodId,goodObj,model=1){
    let chosedFood = {};
    chosedFood = this.getChoseFood() || {};
    console.log("改变用户选中的商品");
    if(model !== 1){
      delete chosedFood[goodId];
    }else{
      chosedFood[goodId] = goodObj;
    }
    wx.setStorage({
      key: 'chosedFood',
      data: chosedFood,
    })
  },
  //从缓存中得到我选中的食物
  getChoseFood:function(){
    let that = this,
        chosedFood = {};
    return wx.getStorageSync("chosedFood")
  },
  //加入订单
  addOrder: function (e) {
    var beizhu = this.data.beizhu;
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    if (e.detail.value.radiogroup == 'wxzf') {
      var is_yue = 2
    }
    if (e.detail.value.radiogroup == 'yezf') {
      var is_yue = 1
    }
    if (e.detail.value.radiogroup == 'chzf') {
      var is_yue = 0
    }
    var that = this
    console.log(that.data);
    var store_id = that.data.store.id
    console.log(store_id);
    var order = that.data.order
    // 获取用户的openid
    var openid = wx.getStorageSync('openid')
    // 获取表单form_id
    var form_id = that.data.form_id
    console.log(form_id)
    // user_id
    var user_id = wx.getStorageSync('users').id
    // 判断用户是否选择优惠券或者代金券
    if (that.data.coupons_id == null) {
      console.log('用户没有选择优惠券')
      var coupons_id = ''
    } else {
      console.log('用户选择了优惠券')
      // 选择的优惠券id
      var coupons_id = that.data.coupons_id
    }
    if (that.data.vouchers_id == null) {
      console.log('用户没有选择代金券')
      var voucher_id = ''
    } else {
      console.log('用户选择了代金券')
      // 选择的代金券id
      var voucher_id = that.data.vouchers_id
    }
    console.log('代金券id' + voucher_id)
    console.log('优惠券id' + coupons_id)
    //  
    var pre = that.data.pre + Number(that.data.cut)
    // 订单金额
    var totalPrice = Number(that.data.totalPrice)
    // 总金额
    var money = Number(that.data.zfmoney)
    console.log(money)
    if (e.detail.value.radiogroup == 'yezf') {
      var ye = Number(this.data.wallet);
      console.log(ye, money)
      if (ye < money) {
        wx.showToast({
          title: '余额不足支付',
          icon: 'loading',
        })
        return
      }
    }
    // var moneys = money
    // 状态
    var type = 2
    console.log(type)
    // 桌号
    var table_id = that.data.table_id
    console.log('桌号' + table_id)
    // 桌子类型
    var tabletype_id = that.data.tabletype_id
    console.log('桌子类型' + tabletype_id)
    var list = []
    order.map(function (item) {
      if (item.num > 0) {
        var obj = {};
        obj.name = item.name;
        obj.img = item.icon;
        obj.num = item.num;
        obj.money = item.money;
        obj.dishes_id = item.id;
        list.push(obj);
      }
    })
    console.log(list)
    // 店内点餐提交订单
    // 提交订单接口
    if (money <= 0) {
      wx: wx.showToast({
        title: '金额不能为0',
        icon: '',
        image: '',
        duration: 2000,
        mask: true,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else {
      this.setData({
        zfz: true,
      })
      app.util.request({
        'url': 'entry/wxapp/AddOrder',
        'cachetime': '0',
        data: { type: type, money: money, user_id: user_id, table_id: table_id, seller_id: store_id, coupons_id: coupons_id, voucher_id: voucher_id, preferential: pre, sz: list, is_yue: is_yue, note: beizhu },
        success: function (res) {
          var order_id = res.data
          console.log('本次的订单id为' + order_id)
          if (order_id != "下单失败") {
            that.setData({
              zfz: false,
              showModal: false,
            })
            if (e.detail.value.radiogroup == 'yezf') {
              console.log('用户选择余额支付')
              // 打印机
              app.util.request({
                'url': 'entry/wxapp/DnPrint',
                'cachetime': '0',
                data: { order_id: order_id, pay_type: '余额支付' },
                success: function (res) {
                  console.log(res)
                },
              })
              app.util.request({
                'url': 'entry/wxapp/DnPrint2',
                'cachetime': '0',
                data: { order_id: order_id, pay_type: '余额支付' },
                success: function (res) {
                  console.log(res)
                },
              })
              // 支付完成发送短信给商家
              app.util.request({
                'url': 'entry/wxapp/sms',
                'cachetime': '0',
                data: { store_id: store_id },
                success: function (res) {
                  console.log(res)

                },
              })
              // 下单改变订单状态
              app.util.request({
                'url': 'entry/wxapp/PayOrder',
                'cachetime': '0',
                data: { user_id: user_id, order_id: order_id, coupons_id: coupons_id, voucher_id: voucher_id },
                success: function (res) {
                  console.log(res)
                  wx.showModal({
                    title: '提示',
                    content: '支付成功',
                    showCancel: false,
                  })
                  setTimeout(function () {
                    wx.switchTab({
                      url: '../list/list'
                    })
                  }, 1000)
                },
              })
            }
            if (e.detail.value.radiogroup == 'wxzf') {
              console.log('用户选择微信支付')
              // 支付接口
              app.util.request({
                'url': 'entry/wxapp/pay',
                'cachetime': '0',
                data: { openid: openid, order_id: order_id, money: money },
                success: function (res) {
                  console.log(res)
                  wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    'success': function (res) {
                      console.log(res.data)
                      console.log(res)
                      wx.showToast({
                        title: '支付成功',
                        duration: 1000
                      })
                      // 打印机
                      app.util.request({
                        'url': 'entry/wxapp/DnPrint',
                        'cachetime': '0',
                        data: { order_id: order_id, pay_type: '微信支付' },
                        success: function (res) {
                          console.log(res)
                        },
                      })
                      app.util.request({
                        'url': 'entry/wxapp/DnPrint2',
                        'cachetime': '0',
                        data: { order_id: order_id, pay_type: '微信支付' },
                        success: function (res) {
                          console.log(res)
                        },
                      })
                      // 支付完成发送短信给商家
                      app.util.request({
                        'url': 'entry/wxapp/sms',
                        'cachetime': '0',
                        data: { store_id: store_id },
                        success: function (res) {
                          console.log(res)

                        },
                      })
                      // 下单改变订单状态
                      app.util.request({
                        'url': 'entry/wxapp/PayOrder',
                        'cachetime': '0',
                        data: { user_id: user_id, order_id: order_id, coupons_id: coupons_id, voucher_id: voucher_id },
                        success: function (res) {
                          console.log(res)
                          wx.showModal({
                            title: '提示',
                            content: '支付成功',
                            showCancel: false,
                          })
                          setTimeout(function () {
                            wx.switchTab({
                              url: '../list/list'
                            })
                          }, 1000)
                        },
                      })
                    }, 'complete': function (res) {
                      wx.showToast({
                        title: '取消支付',
                      })
                      setTimeout(function () {
                        wx.switchTab({
                          url: '../list/list'
                        })
                      }, 1000)
                    }
                  })
                },
              })
            }
            if (e.detail.value.radiogroup == 'chzf') {
              console.log('用户选择餐后支付')
              wx.showModal({
                title: '提示',
                content: '下单成功',
                showCancel: false,
              })
              // 打印机
              app.util.request({
                'url': 'entry/wxapp/DnPrint',
                'cachetime': '0',
                data: { order_id: order_id, pay_type: '餐后支付' },
                success: function (res) {
                  console.log(res)
                },
              })
              app.util.request({
                'url': 'entry/wxapp/DnPrint2',
                'cachetime': '0',
                data: { order_id: order_id, pay_type: '餐后支付' },
                success: function (res) {
                  console.log(res)
                },
              })
              // 支付完成发送短信给商家
              app.util.request({
                'url': 'entry/wxapp/sms',
                'cachetime': '0',
                success: function (res) {
                  console.log(res)

                },
              })
              wx.switchTab({
                url: '../list/list'
              })
            }
          }
        },
      })
    }

  },
  siteInfo:require('siteinfo.js')
});